local socketdriver = require "skynet.socketdriver"
local skynet = require "skynet"

local s = require "service"
local buffer_handler = require "buffer_handler"
local game_cmd = require "cmd_def"
local table_utils = require "table_utils"


s.resp.send_by_fd = function(source, fd, cmd, msg)
    if not s.conns[fd] then
        return
    end

    local pack = buffer_handler.pack_server_data(cmd, msg)
    skynet.error("gate send_by_fd, cmd:" .. cmd .. " len:" ..  string.len(pack) .. " msg:" .. table_utils.table2string(msg))
    socketdriver.send(fd, pack)
end

s.resp.send = function(source, uid, cmd, msg)
    local conn = s.uid2conn[uid]
    if not conn then
        return
    end

    local pack = buffer_handler.pack_server_data(cmd, msg)
    skynet.error("gate send, cmd:" .. cmd .. " len:" ..  string.len(pack) .. " msg:" .. table_utils.table2string(msg))
    socketdriver.send(conn:get_fd(), pack)
end

s.resp.sure_login = function(source, fd, uid, agent)
    local conn = s.conns[fd]
    if not conn then
        -- 登录过程中断线
        skynet.call(source, "lua", "kick", uid, "未完成登陆即下线")
        return false
    end

    conn:set_uid(uid)
    conn:set_agent(agent)

    s.uid2conn[uid] = conn

    return true
end

s.resp.kick = function(source, uid, reason)
    local conn = s.uid2conn[uid]
    if not conn then
        return
    end

    local response = {
        error_code = game_cmd.ERROR_CODE.SUCCESS,
        cmd = game_cmd.SERVER_CMD.COMMON,
        msg = reason or "kick"
    }

    s.resp.send(source, uid, game_cmd.SERVER_CMD.COMMON, response)
    s.disconnect(conn:get_fd())
    socketdriver.close(conn:get_fd())
end
